﻿using KinonekoSoftware.CodariaDB.Documents.Shenanigans.Forum;

namespace KinonekoSoftware.CodariaDB.Documents.Shenanigans
{
    public class ForumEngine : CharacterEngine
    {
        public void Add(Discuss item)
        {
            if (item is null)
            {
                return;
            }

            DiscussCacheDB.Insert(new Discuss
            {
                Id      = item.Id,
                Name    = item.Name,
                Intro   = item.Intro,
                OwnerID = item.OwnerID,
            });
            
            DiscussDB.Insert(item);
        }
        
        public void Update(Discuss item)
        {
            if (item is null)
            {
                return;
            }

            var cache = DiscussCacheDB.FindById(item.Id);

            if (cache is not null)
            {
                cache.Name  = item.Name;
                cache.Intro = item.Intro;
            }

            DiscussDB.Update(item);
            DiscussCacheDB.Update(cache);
        }
        
        public void Remove(Discuss item)
        {
            if (item is null)
            {
                return;
            }

            DiscussDB.Delete(item.Id);
            DiscussCacheDB.Delete(item.Id);
        }

        public IEnumerable<Discuss> GetDiscusses() => DiscussCacheDB.FindAll();

        public Discuss GetDiscuss(Discuss cache)
        {
            if (cache is null)
            {
                return null;
            }

            return DiscussDB.FindById(cache.Id);
        }
        
        protected override void OnDatabaseOpening(RepositoryOpenContext context)
        {
            DiscussDB      = context.Repository.Get<Discuss>(CollectionNames.ForumDB);
            DiscussCacheDB = context.Repository.Get<Discuss>(CollectionNames.Cache_Shenanigans_ForumDB);
            base.OnDatabaseOpening(context);
        }

        protected override void OnDatabaseClosing(ILogger logger)
        {
            DiscussDB      = null;
            DiscussCacheDB = null;
            base.OnDatabaseClosing(logger);
        }

        public ILiteCollection<Discuss> DiscussDB      { get; private set; }
        public ILiteCollection<Discuss> DiscussCacheDB { get; private set; }

        public override string EngineID => EngineNames.Forum;
    }
}